package dao

import (
	"context"
	"forum/app/post/internal/repository/db/model"
	pb "forum/idl/pb/post"
	"forum/pkg/util/logger"
	"gorm.io/gorm"
)

type PostDao struct {
	*gorm.DB
}

func NewPostDao(ctx context.Context) *PostDao {
	return &PostDao{NewDBClient(ctx)}
}

// CreatePost 创建帖子
func (dao *PostDao) CreatePost(req *pb.PostRequest) (err error) {
	t := &model.Post{
		UserId:  uint(req.UserID),
		Title:   req.Title,
		Content: req.Content,
	}
	if err = dao.DB.Model(&model.Post{}).Create(&t).Error; err != nil {
		logger.LoggersObj.Error("Create Post Error:" + err.Error())
		return
	}
	return
}

// UpdatePost 更新帖子
func (dao *PostDao) UpdatePost(req *pb.PostRequest) (err error) {
	t := &model.Post{
		Title:   req.Title,
		Content: req.Content,
	}
	if err = dao.DB.Model(&model.Post{}).Where("user_id = ? AND id = ?", req.UserID, req.PostID).Updates(&t).Error; err != nil {
		logger.LoggersObj.Error("Update Post Error:" + err.Error())
		return
	}
	return
}

// DeletePost 删除帖子
func (dao *PostDao) DeletePost(req *pb.PostRequest) (err error) {
	err = dao.DB.Model(&model.Post{}).Where("user_id = ? AND id = ?", req.UserID, req.PostID).Delete(&model.Post{}).Error
	return
}

// ShowPostByUserId 根据用户ID获取该用户所有帖子
func (dao *PostDao) ShowPostByUserId(req *pb.PostRequest) (post []*model.Post, err error) {
	err = dao.DB.Model(&model.Post{}).Where("user_id = ?", req.UserID).
		Offset(int((req.Page - 1) * req.PageSize)).
		Limit(int(req.PageSize)).
		Order("created_at DESC").
		Find(&post).Error
	return
}

// ShowPostByUserIdAndPostId 根据用户ID和帖子ID获取指定帖子
func (dao *PostDao) ShowPostByUserIdAndPostId(userId uint, postId uint) (post []*model.Post, err error) {
	err = dao.DB.Model(&model.Post{}).Where("user_id = ? AND id = ?", userId, postId).Find(&post).Error
	return
}
